package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import groovy.util.logging.Slf4j;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


/**
 * @author Yandel
 * @date 2025/4/21 上午11:40
 * @description: 学习课程的mq
 */
@lombok.extern.slf4j.Slf4j
@Slf4j
@Component
@RequiredArgsConstructor
public class LessonChangeListener {

    //注入服务
    private final ILearningLessonService learningLessonService;
    /**
     * 监听订单支付或课程报名的消息
     * @param dto 订单信息
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "learning.lesson.pay.queue", durable = "true"),
                    exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE, type = "topic"),
                    key = MqConstants.Key.ORDER_PAY_KEY)
    )
    public void onMsg(OrderBasicDTO dto) {
        log.info(" LessonChangeListener 收到订单支付成功的消息");

        //校验
        if (dto.getUserId() == null ||
                CollUtils.isEmpty(dto.getCourseIds()) ||
                dto.getOrderId() == null
        ) {
            //不要抛异常，否则开启了重试
            return;
        }
        // 2.添加课程
        log.debug("监听到用户{}的订单{}，需要添加课程{}到课表中", dto.getUserId(), dto.getOrderId(), dto.getCourseIds());
        learningLessonService.addUserLesson(dto.getUserId(), dto.getCourseIds());

    }

    /**
     * 退款后，监听到MQ通知，删除指定课程
     * @param order
     */
    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(value = "learning.lesson.refund.queue", durable = "true"),
                    exchange = @Exchange(value = MqConstants.Exchange.ORDER_EXCHANGE, type = ExchangeTypes.TOPIC),
                    key = MqConstants.Key.ORDER_REFUND_KEY
            )
    )
    public  void onRefundMsg(OrderBasicDTO order) {
        //校验
        if (order == null || order.getUserId() == null || CollUtils.isEmpty(order.getCourseIds())) {
            //不要抛异常，否则开启了重试
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        // 2.删除课程
        log.debug("监听到用户{}的订单{}要退款，需要删除课程{}", order.getUserId(), order.getOrderId(), order.getCourseIds());
        learningLessonService.deleteLearningLesson(order.getUserId(), order.getCourseIds().get(0));
    }

}
